﻿using System;
using System.Diagnostics;

namespace nhCore.Modbus
{
    /// <summary>
    /// 气象帧04、041H的时间解码器类
    /// </summary>
    public class TimeDecoder : Decoder
    {
        /// <summary>
        /// 新建日期解码器实例
        /// </summary>
        public TimeDecoder()
        {
            Name = "日期解码器";
            Config = new ElementConfig
            {
                Type = CoreGlobal.Const_time,
                Display = "时间",
                Unit = string.Empty,
                Index = CoreGlobal.Const_TimeIndex,
            };
        }

        public override string Convert(double value)
        {
            return ConvertWeather(value);
        }

        /// <summary>
        /// 转换显示
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override string ConvertWeather(double value)
        {
            return new DateTime((long)value, DateTimeKind.Local).ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 解析modbus中的时间
        /// </summary>
        /// <param name="mb"></param>
        /// <returns></returns>
        public override double? DeCode(FrameValid mb)
        {
            DateTime dt = new DateTime();
            if (mb == null)
            {
                Debug.WriteLine(Name + "：mb为null");
            }
            else if (!mb.IsValid)
            {
                Debug.WriteLine(Name + "：mb效验失败");
            }
            else
            {
                try
                {
                    int i = 0;
                    int y = 2000 + mb.Data[i];
                    int m = mb.Data[++i];
                    int d = mb.Data[++i];
                    int h = mb.Data[++i];
                    int min = mb.Data[++i];
                    int s = mb.Data[++i];

                    dt = new DateTime(y, m, d, h, min, s);
                }
                catch (Exception)
                {
                    Debug.WriteLine(Name + "：时间解析失败");
                    return 0;
                }
            }
            return dt.Ticks;
        }
    }

    /// <summary>
    /// 传感器接软件，传感器无时间，读计算机时间
    /// </summary>
    public class CgqTimeDecoder : TimeDecoder
    {
        public override double? DeCode(FrameValid mb)
        {
            return DateTime.Now.Ticks;
        }
    }
}
